package cn.edu.scau.cmi.front.controller;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import cn.edu.scau.cmi.ema.domain.Feature;
import cn.edu.scau.cmi.ema.domain.Standard;
import cn.edu.scau.cmi.ema.domain.Standardlevel;
import cn.edu.scau.cmi.ema.domain.Standardtype;
import cn.edu.scau.cmi.ema.domain.base.CmiPagination;
import cn.edu.scau.cmi.ema.util.CmiSqlUtil;
import cn.edu.scau.cmi.ema.util.CmiHibernateProxyUtil;

@Controller("FrontKnowledgeBaseController")

public class FrontKnowledgeBaseController extends FrontCmiEmaController {

	

	@RequestMapping("/frontCheckKnowledgeBaseForFeature")
	public ModelAndView frontCheckKnowledgeBaseForFeature(@ModelAttribute CmiPagination page) {

		ModelAndView mav = new ModelAndView();


		Set<String> basicAttributes = null;//featurePaginationService.getFeatureBasicAttributes();
		Set<Feature> features = null;//featurePaginationService.getFeatureRecords(page);

		mav.addObject("basicAttributes", basicAttributes);

		mav.addObject("basicAttributesSize", basicAttributes.size());

		mav.addObject("features", features);

		mav.addObject("page", page);

		mav.addObject("entityName", "Feature");

		mav.setViewName("front/frontCheckKnowledgeBaseForFeature.jsp");

		return mav;
	}
	
	@RequestMapping("/frontCheckKnowledgeBaseForStandard")
	public ModelAndView frontCheckKnowledgeBaseForStandard(@ModelAttribute CmiPagination page) {

		ModelAndView mav = new ModelAndView();


		Set<String> basicAttributes = null;//standardPaginationService.getStandardBasicAttributes();
		Set<Standard> standards = null;//standardPaginationService.getStandardRecords(page);

		mav.addObject("basicAttributes", basicAttributes);

		mav.addObject("basicAttributesSize", basicAttributes.size());

		mav.addObject("standards", standards);

		mav.addObject("page", page);

		mav.addObject("entityName", "Standard");

		mav.setViewName("front/frontCheckKnowledgeBaseForStandard.jsp");

		return mav;
	}
	
	@RequestMapping("/frontKnowledgeBaseForStandardDetail")
	public ModelAndView frontKnowledgeBaseForStandardDetail(@RequestParam Integer featureId) {
		ModelAndView mav = new ModelAndView();

		Set<Standard> standards = cmiFeaturestandardDAO.findStandardsByFeatureId(-1, -1, featureId);
		System.out.println("standards==>>"+standards);
		mav.addObject("standards", standards);
		mav.setViewName("front/frontKnowledgeBaseForStandardDetail.jsp");

		return mav;
	}
	
	@RequestMapping("/frontKnowledgeBaseForFeatureDetail")
	public ModelAndView frontKnowledgeBaseForFeatureDetail(@RequestParam Integer standardId) {
		System.out.println("standardId==>>"+standardId);
		ModelAndView mav = new ModelAndView();

		Set<Object> objects = cmiFeaturestandardDAO.findFeaturesByStandardId(-1, -1, standardId);
		
		mav.addObject("objects", objects);
		mav.setViewName("front/frontKnowledgeBaseForFeatureDetail.jsp");

		return mav;
	}
	@RequestMapping("/frontCheckKnowledgeBaseItems")
	public ModelAndView frontCheckKnowledgeBaseItems(@ModelAttribute CmiPagination page) {
		ModelAndView mav = new ModelAndView();


		Set<String> basicAttributes = frontService.getKnowledgeBaseBasicAttributes();
		Set<Object> objects = frontService.getRecordsForKnowledgeBase(page);

		mav.addObject("basicAttributes", basicAttributes);

		mav.addObject("basicAttributesSize", basicAttributes.size());

		mav.addObject("objects", objects);

		mav.addObject("page", page);

		mav.setViewName("front/frontCheckKnowledgeBaseItems.jsp");
		return mav;
	}

	// 知识库：检测标准。
	@RequestMapping("/frontDetectKnowledgeBaseItems")
	public ModelAndView frontDetectKnowledgeBaseItems(@ModelAttribute CmiPagination page) {
		ModelAndView mav = new ModelAndView();

		Set<String> basicAttributes = frontService.getKnowledgeBaseBasicAttributes();
		Set<Object> objects = frontService.getRecordsForKnowledgeBase(page);

		mav.addObject("basicAttributes", basicAttributes);

		mav.addObject("basicAttributesSize", basicAttributes.size());

		mav.addObject("objects", objects);

		mav.addObject("page", page);

		mav.setViewName("front/frontDetectKnowledgeBaseItems.jsp");
		return mav;
	}
	
	
	//	TODO 标准的提交与修改。这里是单个文件，不需要使用MultipartFile[]！！！，过一会再测试
	@RequestMapping(value = "/saveStandardWithFileByForm", method = RequestMethod.POST)
	public ModelAndView saveStandardWithFileByForm(@RequestParam("standardFile") MultipartFile[] multipartFiles,	@ModelAttribute Standard standard) throws IOException {
//		保存文件，文件名使用standard的name属性，以免文件名称不合理，不使用上传的文件名称，使用在编辑界面所定义的文件名。
		String fileName=standardUploaDirectory+"/"+standard.getName();
		frontService.saveUploadFiles(Arrays.asList(multipartFiles), standardUploaDirectory, fileName);
	//TODO  转发到/saveStandard？？？？？？
		ModelAndView mav = new ModelAndView();
//		从

		Standard replacedstandardTemp = standard.getReplacedstandard();
		Standard replacedstandard = replacedstandardTemp == null ? null
				: CmiHibernateProxyUtil.deproxy(standardDAO.findStandardById(replacedstandardTemp.getId()));
		Standardtype standardtypeTemp = standard.getStandardtype();
		Standardtype standardtype = standardtypeTemp == null ? null
				: CmiHibernateProxyUtil.deproxy(standardtypeDAO.findStandardtypeById(standardtypeTemp.getId()));
		Standardlevel standardlevelTemp = standard.getStandardlevel();
		Standardlevel standardlevel = standardlevelTemp == null ? null
				: CmiHibernateProxyUtil.deproxy(standardlevelDAO.findStandardlevelById(standardlevelTemp.getId()));

		Standard existingStandard = CmiHibernateProxyUtil.deproxy(standardDAO.findStandardByPhysicalPrimaryKey(
				standard.getNumber()));

		standard.setReplacedstandard(replacedstandard);
		standard.setStandardtype(standardtype);
		standard.setStandardlevel(standardlevel);
		// 新建记录
		if (standard.getId() == null) {
			if (standard.equals(existingStandard)) {

				mav.addAllObjects(standardService.loadStandardClassReferencedSet(standard));
				// mav = editContinue(mav, standard);
				mav.addObject("isInsertSuccess", "false");
				mav.setViewName("standard/editStandard.jsp");
			} else {
				standardService.saveStandard(standard);
				mav.setViewName("forward:/listStandards");
			}
		}
		// 编辑记录
		else {
			Standard originStandard = CmiHibernateProxyUtil
					.deproxy(standardDAO.findStandardByPrimaryKey(standard.getId()));
			if (!standard.equals(originStandard) && standard.equals(existingStandard)) {
				mav.addAllObjects(standardService.loadStandardClassReferencedSet(standard));
				mav.addObject("isInsertSuccess", "false");
				mav.setViewName("standard/editStandard.jsp");
			} else {
				standardService.saveStandard(standard);
				mav.setViewName("forward:/listStandards");
			}
		}
		return mav;
	}

	


	/**
	 * 
	 * @param multipartFile 批量检测，根据用户选择来显示结果
	 * @return
	 */
	@RequestMapping(value = "/frontUploadExcelForKnowledgeBase", method = RequestMethod.POST)
	public ModelAndView frontUploadExcelForKnowledgeBase(@RequestParam("load-excel") MultipartFile multipartFile,
			HttpServletRequest request,@ModelAttribute CmiPagination page) {
		ModelAndView mav = new ModelAndView();

		List<String> featureNames = new ArrayList<>();
		List<String> unitNames = new ArrayList<>();
		List<Double> values = new ArrayList<>();
		
		

		BufferedInputStream bf = null;
		try {
			bf = new BufferedInputStream(multipartFile.getInputStream());
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		XSSFWorkbook workbook = null;
		try {
			workbook = new XSSFWorkbook(bf);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		XSSFSheet sheet = workbook.getSheetAt(0);

		int firstrow = sheet.getFirstRowNum();
		// 获取最后一行
		int lastrow = sheet.getLastRowNum();
		// 循环行数依次获取列数
		for (int i = firstrow + 1; i < lastrow + 1; i++) {
			// 获取哪一行i
			Row row = sheet.getRow(i);
			if (row != null) {
				// 获取这一行的第一列
				int firstcell = row.getFirstCellNum();
				// 获取这一行的最后一列
				int lastcell = row.getLastCellNum();

				for (int j = firstcell; j < lastcell; j++) {
					// 获取第j列
					Cell cell = row.getCell(j);

					if (cell != null) {
						if (j == 0) { // featureName
							featureNames.add(cell.toString());
						}
						if (j == 1) {// value
							NumberFormat nf = NumberFormat.getInstance();
							String s = nf.format(cell.getNumericCellValue());
							values.add(Double.valueOf(s));
						}
						if (j == 2) { // unitName
							unitNames.add(cell.toString());
						}
					}
				}
			}
		}

//		String sqlString = CmiSqlUtil.appendConditions4Knowledge(featureNames, unitNames);
		
		System.out.println(featureNames);
		System.out.println(values);
		System.out.println(unitNames);
		//standard.name 
		//standardlevel.name-->>feature.value-->1
		//standardtype.name-->>result.name-->2
		//standard.effectivedate
		//standard.expirydate
		//feature.name-->5
		//unit.name-->6
		//featurestandard.min-->7
		//featurestandard.max-->8
		
		Set<String> basicAttributes = frontService.getKnowledgeBaseBasicAttributes();
//		Set<Object> objects = frontService.getRecordsForKnowledgeBaseByFeature(page,sqlString);

//		objects = featureValueCheck(objects,featureNames,unitNames,values);
		
		mav.addObject("basicAttributes", basicAttributes);

		mav.addObject("basicAttributesSize", basicAttributes.size());

//		mav.addObject("objects", objects);
		
		mav.addObject("page", page);
		
		mav.setViewName("front/frontDetectResultForKnowledgeBase.jsp");
		return mav;
	}

	public Set<Object> featureValueCheck(Set<Object> objects,List<String> featureNames,List<String> unitNames,List<Double> values) {
		String featureName = null;
		String unitName = null;
		String qualified = "合格";
		String unqualified = "不合格";
		String unknown = "未知";
		List<Integer> matchList = new ArrayList<>();
		for(int i=0;i<featureNames.size();i++) {
			featureName = featureNames.get(i);
			unitName = unitNames.get(i);
			for(Object ob:objects) {
				if((((Object[])ob)[5]).equals(featureName) && (((Object[])ob)[6]).equals(unitName)) {
					matchList.add(i);
					if((Float)(((Object[])ob)[7])<=values.get(i) && (Float)(((Object[])ob)[8])>=values.get(i)) {
						(((Object[])ob)[1]) = values.get(i);
						(((Object[])ob)[2]) = qualified;
					}else {
						(((Object[])ob)[1]) = values.get(i);
						(((Object[])ob)[2]) = unqualified;
					}
				}
			}
		}

		for(Integer index :matchList) {
			featureNames.remove(index);
			unitNames.remove(index);
			values.remove(index);
		}
		
		for(int j=0;j<featureNames.size();j++) {
			Object[] object = new Object[9];
			object[5] = featureNames.get(j);
			object[1] = values.get(j);
			object[6] = unitNames.get(j);
			object[2] = unknown;
			object[3] = null;
			object[4] = null;
			object[7] = null;
			object[8] = null;
			object[0] = null;
			objects.add((Object)object);
		}
		
		
		return objects;
	}
}